package com.manager.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil {
	public final static String YYYY_MM = "yyyy-MM";

	public final static String YYYY_MM_DD = "yyyy-MM-dd";

	public final static String HH_MM_SS = "HH:mm:ss";

	public final static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

	/**
	 * 取得年份月份，形式如："2010-01"或"201001"
	 * 
	 * @param withSeparator
	 *            true:含有分隔符"-";false:不含分隔符"-"
	 * @return java.lang.String
	 */
	public static String getCurrentYearMonth(boolean withSeparator) {
		return new SimpleDateFormat(withSeparator == true ? YYYY_MM : deleteSaparator(YYYY_MM)).format(new Date());
	}

	/**
	 * 取得日期，形式如："2010-01-01"或"20100101"
	 * 
	 * @param withSeparator
	 *            true:含有分隔符"-";false:不含分隔符"-"
	 * @return java.lang.String
	 */
	public static String getCurrentDate(boolean withSeparator) {
		return new SimpleDateFormat(withSeparator == true ? YYYY_MM_DD : deleteSaparator(YYYY_MM_DD)).format(new Date());
	}

	/**
	 * 取得时间，形式如："22:30:56"或"223056"
	 * 
	 * @param withSeparator
	 *            true:含有分隔符"-";false:不含分隔符"-"
	 * @return java.lang.String
	 */
	public static String getCurrentTime(boolean withSeparator) {
		return new SimpleDateFormat(withSeparator == true ? HH_MM_SS : deleteSaparator(HH_MM_SS)).format(new Date());
	}

	/**
	 * 取得日期时间，形式如："2010-01-01 22:30:56"或"20100101223056"
	 * 
	 * @param withSeparator
	 *            true:含有分隔符"-";false:不含分隔符"-"
	 * @return java.lang.String
	 */
	public static String getCurrentDateTime(boolean withSeparator) {
		return new SimpleDateFormat(withSeparator == true ? YYYY_MM_DD_HH_MM_SS : deleteSaparator(YYYY_MM_DD_HH_MM_SS)).format(new Date());
	}
	
	/**
	 * 由字符串得到Date类型，格式如："yyyy-MM-dd HH:mm:ss"
	 */
	public static Date getDateTime(String dateTime) throws ParseException {
		return new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS).parse(dateTime);
	}
	
	/**
	 * 由字符串得到Date类型，格式如："yyyy-MM-dd"
	 */
	public static Date getDate(String date) throws ParseException {
		return new SimpleDateFormat(YYYY_MM_DD).parse(date);
	}
	
	/**
	 * 由字符串得到int类型，格式如："yyyyMMdd"
	 */
	public static int getDateInt(String dateTime) throws ParseException {
		return Integer.parseInt(DateUtil.deleteSaparator(dateTime));
	}
	
	/**
	 * 由字符串得到long类型，格式如："yyyyMMddHHmmss"
	 */
	public static long getDateTimeLong(String dateTime) throws ParseException {
		return Long.parseLong(DateUtil.deleteSaparator(dateTime));
	}
	
	/**
	 * 辅助函数，用来删除2010-12-30中的"-"，" "，":"
	 * @param str
	 * @return
	 */
	public static String deleteSaparator(String str) {
		return new Stringbuffer(str).replaceAll(new String[] { "-", " ", ":" }, new String[] { "" }).toString();
	}

	public static void main(String[] args) throws ParseException {
		System.out.println(DateUtil.getDateTimeLong("2010-04-10 06:10:59"));
	}
}
